<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2017-11-01
 * Time: 15:51
 * @desc   商城后台 -- 库存管理
 */
namespace app\mall\controller;
use controller\BasicAdmin;
use service\DataService;
use app\mall\model\StoreMaterialOrder;
use app\mall\model\StoreChengpinOrderr;
use app\mall\model\MaterialStockLog;
use app\mall\model\GoodsMaterial;
use app\mall\model\Goods as Goodsmodel;
use app\mall\model\GoodsStockLog;
use app\mall\model\StoreOrderGoods;
use app\mall\model\GoodsSpecDetail;
use think\Db;
use think\Request;
class Stock extends BasicAdmin
{
	/**
	 * 变更库存
	 * @return [type] [description]
	 */
	public function change_stock(){
		if(request()->isPost()){
			$data = input('post.');
			$material = Db::name('goods_material')->where('id',$data['material_id'])->find();
			if($data['sign'] == 1){		//入库
				$data['type'] = 1;		//类型：增加
				$data['material_type'] = 1;		//原料进货
				$data['dif_num'] = $data['del_num'] - $data['res_num'];
				$data['cur_num'] = $material['stock'] + $data['res_num'];
			}else{			//报损
				$data['type'] = 2;		//类型：减少
				$data['material_type'] = 1;		//原料出库
				$data['res_num'] = $data['dif_num'];
				$data['cur_num'] = $material['stock'] - $data['dif_num'];
				if($data['dif_num'] > $material['stock']){
					$this->error('报损数不能大于当前库存','');			//报损数不能大于当前库存
				}
			}
			$res = Db::name('goods_material')->update(['id'=>$data['material_id'],'stock'=>$data['cur_num']]);
			if($res!==false){
				$res = Db::name('material_stock_log')->insert($data);
				$res>0?$this->success('保存成功',''):$this->error('保存失败,请重试','');
			}
		}else{
			$id = input('id');
			$table = "MaterialStockLog";
			$material = Db::name('goods_material')->where('id',$id)->find();
			$this->assign('time',time());
			$this->assign('material',$material);
			// return $this->fetch('add_stock_log');
	        return $this->_form($table, 'change_stock');	
		}
	}
	/**
	 * 库存变更日志
	 * $desc   自定义方法
	 * @return [type] [description]
	 */
	public function stock_log(){
  		$this->title = '库存变更日志';
      	$get = request()->get();
        $map = array();
		// $map['material_type'] = array('eq',1);
        if(!empty($get['goods_id'])){
        	$this->assign('goods_id',$get['goods_id']);
            $map['a.goods_id'] = array('eq',$get['goods_id']);
        }else{
        	$this->assign('goods_id',0);
        }
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('goods_stock_log')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_store c','a.store_id=c.id','LEFT')->join('ys_goods_spec_detail d','a.goods_spec_id=d.id','LEFT')->where($map)->field('a.*,b.name,c.title,d.title as spec_name')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $goods = Db::name('goods')->where('is_deleted',0)->select();
        $this->assign('title',$this->title);
        $this->assign('goods',$goods);
        // $this->assign('list',$result['list']);
        // $this->assign('page',$result['page']);
        if(!isset($get['export'])){
        	return $this->fetch('stock_log', $result);
        }else{
        	$data = Db::name('material_stock_log')->alias('a')->join('ys_goods_material b','a.material_id=b.id','LEFT')->join('ys_store c','a.store_id=c.id','LEFT')->where($map)->field('a.*,b.name,c.title')->select();
        	$this->export($data);
        }
	}
	/**
	 * 导出文件
	 * @return [type] [description]
	 */
	private function export($data){
		$table = '';
		$table .= "<table><thead><tr><th>".iconv('UTF-8', 'GB2312','原料名称')."</th><th>".iconv('UTF-8', 'GB2312','门店')."</th>
                    <th>".iconv('UTF-8', 'GB2312','类型')."</th><th>".iconv('UTF-8', 'GB2312','变更数')."</th><th>".iconv('UTF-8', 'GB2312','当前库存')."</th>
                    <th>".iconv('UTF-8', 'GB2312','变更时间')."</th></tr></thead><tbody>";
            foreach ($data as $v) {
            $table .= "<tr>
                    <td>".iconv('UTF-8', 'GB2312',$v['name'])."</td>";
            if(!empty($v['title'])){
            	$table .="<td>".iconv('UTF-8', 'GB2312',$v['title'])."</td>";
            }else{
            	$table .="<td>".iconv('UTF-8', 'GB2312','无')."</td>";
            }
            if($v['sign'] == 1){
            	$table .="<td>".iconv('UTF-8', 'GB2312','进货')."</td>";
            }else if($v['sign'] == 2){
            	$table .="<td>".iconv('UTF-8', 'GB2312','提货')."</td>";
            }else if($v['sign'] == 3){
            	$table .="<td>".iconv('UTF-8', 'GB2312','报损')."</td>";
            }
            if($v['type'] == 1){
            	$table .="<td>+".iconv('UTF-8', 'GB2312',$v['res_num'])."</td>";
            }else{
            	$table .="<td>-".iconv('UTF-8', 'GB2312',$v['res_num'])."</td>";
            }
            $table .="<td>".iconv('UTF-8', 'GB2312',$v['cur_num'])."</td>";
           	$time = date('Y-m-d H:i',$v['addtime']);
           	$table .="<td>".iconv('UTF-8', 'GB2312',$time)."</td></tr>";
        }
        $table .= "</tbody></table>";
        header("Pragma: public");  
        header("Expires: 0");  
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");  
        header("Content-Type:application/force-download");  
        header("Content-Type:application/vnd.ms-execl");  
        header("Content-Type:application/octet-stream");  
        header("Content-Type:application/download");;  
        header('Content-Disposition:attachment;filename="库存明细表.xls"');  
        header("Content-Transfer-Encoding:binary");  
        echo $table;exit();
	}	

	/**
	 * 门店申请原料购货订单 -- 列表
	 * @return [type] [description]
	 */
	public function apply_order(){
		$this->title = '购货申请处理';
        $get = $this->request->get();
        $map = array();
        $map['a.status'] = array('neq',4);
        $map['a.type'] = array('in','0,1');
        $map['a.is_deleted'] = array('eq',0);
        if(!empty($get['store_id'])){
        	$this->assign('store_id',$get['store_id']);
            $map['a.store_id'] = array('eq',$get['store_id']);
        }else{
        	$this->assign('store_id',0);
        }
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $page = Db::name('store_order')->alias('a')->join('store b','a.store_id=b.id','LEFT')->where($map)->field('a.*,b.title')->order('a.id desc')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $this->assign('title',$this->title);			//必须加上title,不然顶部的按钮不会显示
        return $this->fetch('apply_order', $result);
	}
	/**
	 * 原料购货订单详情  -- 列表
	 * @return [type] [description]
	 */
	// public function order_peifang(){
	// 	$order_id = input('id');
	// 	$status = Db::name('store_order')->where('id',$order_id)->value('status');
	// 	$db = Db::name('store_order_goods')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_store c','a.store_id=c.id','LEFT')->where('a.order_id',$order_id)->field('a.*,b.name,c.title');
	// 	$this->assign('title','详情');		
	// 	$this->assign('status',$status);
	// 	$this->assign('orderid',$order_id);
	// 	return parent::_list($db);
	// }
	/**
	 * 购货申请订单详情,原材料购货或者自行订货表
	 * @lingyun
	 * @return [type] [description]
	 */
	public function order_detail(){
		$this->title = '订单详情';
		$id = input('id');
        $get = $this->request->get();
        $map = array();
        $map['a.is_deleted'] = array('eq',0);
        $map['a.order_id'] = array('eq',$id);
        $rows = intval($this->request->get('rows', cookie('rows')));
        cookie('rows', $rows >= 10 ? $rows : 20);
        $status = Db::name('store_order')->where('id',$id)->value('status');
        $page = Db::name('store_order_goods')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where($map)->field('a.*,b.name,b.unit,c.title')->paginate($rows, false, ['query' => request()->get('', '', 'urlencode')]);
        list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
        list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())]; 
        $this->assign('title',$this->title);			//必须加上title,不然顶部的按钮不会显示
        $this->assign('id',$id);
        $this->assign('status',$status);
        return $this->fetch('order_detail', $result);
	}
	/**
	 * 处理门店订货申请，原料购货申请处理 -- 表单
	 * 修改订单状态、发货数量、总后台库存日志记录
	 * @lingyun
	 * @return [type] [description]
	 */
	public function deal_send(){
		if(request()->isPost()){
			$data = input('post.');
			$result = $this->StoreOrderGoodsData($data);		//构造数据
			// halt($result);exit();
			// halt($result);
			if($result['code'] == 1){
				$model1 = new StoreOrderGoods();
				$model2 = new GoodsStockLog();
				$model3 = new GoodsSpecDetail();
				$model1->saveall($result['data']['data1']);
				$model2->saveall($result['data']['data2']);
				$model3->saveall($result['data']['data3']);
				$res = Db::name('store_order')->where('id',$data['orderid'])->update(['deal_time'=>time(),'status'=>1]);
				$res!==false?$this->success('处理成功',''):$this->error('处理失败','');
			}else{
				$this->error($result['msg'],'');
			}
			
			// $s_model = new StoreMaterialOrder();
			// $gm_model = new GoodsMaterial();
			// $msl_model = new MaterialStockLog();
			// $result = $s_model->save_order($data);		//修改发货记录
			// if($result['code'] == 1){
			// 	$s_model->save_order($data);		//更新门店发货数
			// 	$gm_model->save_order($data);		//更新总店原料库存数
			// 	$msl_model->save_order($data);		//记录总店原料库存记录
			// 	$res = Db::name('store_order')->where('id',$data['order_id'][0])->update(['deal_time'=>time(),'status'=>1]);		//更新订单未发货状态
			// 	$res!==false?$this->success('发货成功',''):$this->errro('发货失败','');
			// }else{
			// 	$this->error($result['msg'],'');			//库存不足的情况
			// }
		}else{
			$orderid = input('id');			//订单id
			$list = Db::name('store_order_goods')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->join('ys_goods_spec_detail c','a.goods_spec_id=c.id','LEFT')->where('a.order_id',$orderid)->field('a.*,b.name,b.unit,c.stock,c.title')->select();		//查询订单详情
			// halt($list);
			$this->assign('list',$list);
			$this->assign('orderid',$orderid);
			$this->assign('title','发货处理');
			return $this->fetch('deal_send');
		}
	}
	/**
	 * 驳回申请
	 * @lingyun
	 * @return [type] [description]
	 */
	public function deal_rebat(){
		$orderid = input('id');
		if(request()->isPost()){
			$da = input('post.');
			// $material = Db::name('store_order')->where('order_id',$orderid)->select();
			// $s_model = new StoreMaterialOrder();
			// $result = $s_model->rebut($material);
			// if($result['code'] == 1){
				$res = Db::name('store_order')->where('id',$orderid)->update(['deal_time'=>time(),'status'=>2,'remark'=>$da['remark']]);
				$res!==false?$this->success('已驳回',''):$this->error('驳回失败','');
			// }
		}else{
			$this->assign('orderid',$orderid);
			return $this->fetch('deal_rebat');
		}
	}
	/**
	 * 门店购货详情表入库数据
	 * $res1  是更新store_order_goods的数据
	 * $res2  是总后台的库存日志数据
	 * $res3  更新总后台的商品对应属性库存的数据
	 * @Author   lingyun
	 * @DateTime 2017-12-05T17:31:33+0800
	 */
	private function StoreOrderGoodsData($post){
		foreach($post['stock'] as $k => $v){
			if($v < $post['del_num'][$k]){
				return ['code'=>0,'msg'=>$post['goods_name'][$k].'库存不足','data'=>array()];
				break;
			}		
			$res1[$k]['id'] = $post['id'][$k];		//主键id
			$res1[$k]['del_num'] = $post['del_num'][$k];
			$res1[$k]['deal_time'] = time();		


			$res2[$k]['goods_id'] = $post['goods_id'][$k];	
			$res2[$k]['goods_spec_id'] = $post['goods_spec_id'][$k];
			$res2[$k]['store_id'] = $post['store_id'][$k];
			$res2[$k]['sign'] = 2;		//门店发货
			$res2[$k]['type'] = 2;		//减少
			$res2[$k]['del_num'] = $post['del_num'][$k];		//发货数量
			$res2[$k]['rec_num'] = $post['del_num'][$k];		//实际发货数量
			$res2[$k]['dif_num'] = 0;		//差异数
			$res2[$k]['cur_num'] = $post['stock'][$k]-$post['del_num'][$k];		//当前库存
			$res2[$k]['remark'] = '';
			$res2[$k]['addtime'] = time();


			$res3[$k]['id'] = $post['goods_spec_id'][$k];		//商品属性详情id
			$res3[$k]['stock'] = $post['stock'][$k]-$post['del_num'][$k];
		}
		return ['code'=>1,'msg'=>'','data'=>array('data1'=>$res1,'data2'=>$res2,'data3'=>$res3)];		//返回给更新的数据
	}

	/**
	 * 自行订货处理表
	 * @return [type] [description]
	 */
	public function zx_order(){
		$this->title = '成品购货申请';
		$table = "StoreOrder";
        $get = $this->request->get();
        $join = [
            ['ys_store b', 'a.store_id=b.id', 'LEFT'],
        ];
        $map['a.is_deleted'] = array('eq',0);
        $map['a.type'] = array('eq',1);
        if(!empty($get['sn'])){
        	$map['a.sn'] = array('like','%'.$get['sn'].'%');		//订单号搜索
        }
        $db = Db::name($table)->alias('a')->join($join)->where($map)->field('a.id,a.sn,a.store_id,a.status,a.deal_time,a.addtime,b.title');
        return parent::_list($db);
	}
	/**
	 * 自行商品购货申请详情表
	 * @return [type] [description]
	 */
	public function zx_orderdetail(){
		$this->title = '订单详情';
		$id = input('id');		//订单id
		$table = "StoreMaterialApply";
        $get = $this->request->get();
        $map = array();
        $map['a.is_deleted'] = array('eq',0);
        // $map['a.order_id'] = array('eq',$id);
        // $join = [
        // 	['ys_store_order b','a.order_id=b.id','LEFT'],
        // 	['ys_goods c','a.goods_id=c.id','LEFT']
        // ];
        $db = Db::name($table)->alias('a')->join('ys_store b','a.store_id=b.id','LEFT')->where($map)->field('a.*,b.title');
        $this->assign('orderid',$id);
        return parent::_list($db);
	}
	/**
	 * 自行购货订单详情
	 * 操作订单流水账表
	 * 记录订单流水账记录
	 * @return [type] [description]
	 */
	public function deal_zxorder(){
		if(request()->isPost()){
			$post = input('post.');
			$res = Db::name('store_order')->where('id',$post['order_id'])->update(['deal_time'=>time(),'remark'=>$post['remark']]);
			$res!==false?$this->success('保存成功',''):$this->error('处理失败','');
			// $data = input('post.');
			// $s_model = new StoreChengpinOrderr();
			// $log_model = new MaterialStockLog();
			// $goods_model = new Goodsmodel();
			// $result = $s_model->save_order($data);		//修改发货记录
			// if($result['code'] == 1){
			// 	$log_model->save_order($data);
			// 	$da = $goods_model->update_order($data);
			// 	foreach($da as $k => $v){
			// 		Db::name('goods')->update($v);
			// 	}
			// 	$res = Db::name('store_order')->where('id',$data['order_id'][0])->update(['deal_time'=>time(),'status'=>1,'amount'=>$data['amount'],'remark'=>$data['remark']]);		//更新订单未发货状态
			// 	$res!==false?$this->success('同意申请',''):$this->error('驳回申请','');
			// }else{
			// 	$this->error($result['msg'],'');			//库存不足的情况
			// }
		}else{
			$orderid = input('id');
			$amount = Db::name('store_material_apply')->where('order_id',$orderid)->field('sum(amount) as amount')->select();
			// $list = Db::name('store_material_apply')->alias('a')->join('ys_goods b','a.goods_id=b.id','LEFT')->where('a.order_id',$orderid)->field('a.*,b.name,b.unit,b.stock')->select();		//查询订单详情
			// $this->assign('list',$list);
			$this->assign('orderid',$orderid);
			$this->assign('amount',$amount[0]['amount']);
			return $this->fetch('deal_zxorder');
		}
	}
	/**
	 * 驳回订单
	 * @return [type] [description]
	 */
	public function rebut_zxorder(){
		$orderid = input('id');
		if(request()->isPost()){
			$da = input('post.');
			// $material = Db::name('store_material_order')->where('order_id',$orderid)->select();
			// $s_model = new StoreChengpinOrder();
			// $result = $s_model->rebut($material);
			// if($result['code'] == 1){
				$res = Db::name('store_order')->where('id',$orderid)->update(['deal_time'=>time(),'status'=>2,'remark'=>$da['remark']]);
				$res!==false?$this->success('已驳回',''):$this->error('驳回失败','');
			// }
		}else{
			$this->assign('orderid',$orderid);
			return $this->fetch('rebut_zxorder');
		}
	}
	/**
	 * 修改安全库存
	 * @return [type] [description]
	 */
	public function change_warn(){
		$table = 'GoodsMaterial';
        return $this->_form($table, 'change_warn');
	}
	/**
	 * 安全库存详情
	 * @return [type] [description]
	 */
	public function warn_detail(){
		$this->title = '原材料分类';
        $get = $this->request->get();
        $db = Db::name('goods_material')->where('is_deleted',0);			
        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }
        return parent::_list($db);
	}

}
?>